package com.woniu.car.advice;

import com.woniu.car.common.JWTUtil;
import com.woniu.car.common.ResponseEntity;
import com.woniu.car.exception.AccountException;
import com.woniu.car.exception.ParamException;
import com.woniu.car.feign.AccountClient;
import com.woniu.car.parameter.QueryRolePermissionParam;
import com.woniu.car.util.Code;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Enumeration;

/**
 * @ClassName MyAdvice
 * @Description
 * @Author 王维鑫
 * @Version
 **/
@Aspect
@Component
public class MyAdvice {
    @Resource
    private AccountClient accountClient;
    //后台权限校验
    @Before("@annotation(com.woniu.car.annotation.BackstagePermissionCheck)")
    public void backstagePermissionCheck(JoinPoint joinPoint) throws Exception {
        Object[] args = joinPoint.getArgs();
        HttpServletRequest request=null;
        String uri="";
        for (int i=0;i<args.length;i++){
            if(args[i] instanceof HttpServletRequest){
                request= (HttpServletRequest) args[i];
            }
        }
        String token = request.getHeader("token");
        uri=request.getRequestURI();
        //得到后台用户ID
        String i= JWTUtil.getId(token);
        Integer id=Integer.getInteger(i);
        QueryRolePermissionParam queryRolePermissionParam = new QueryRolePermissionParam();
        queryRolePermissionParam.setUri(uri);
        queryRolePermissionParam.setUserId(id);
        ResponseEntity responseEntity = accountClient.queryRolePermission(queryRolePermissionParam);
        Integer code = responseEntity.getCode();
        System.out.println("返回："+code);
        if(code.equals(Code.ERROR)){
            throw new AccountException("您无权访问此接口");
        }
    }
}
